package com.genentech.bioinformatics.mobi;
/*
 * Class by Jeff Milton, except where otherwise noted.
 */
import com.genentech.flexigraph.Grid;

import android.graphics.Color;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;

public class AnnotateGestureDetection extends SimpleOnGestureListener {
	private static final int SWIPE_MAX_OFF_PATH = 10;
	private AnnotatePanel annotatePanel = null;

	public AnnotateGestureDetection(AnnotatePanel _annotatePanel) {
		super();
		annotatePanel = _annotatePanel;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		int dist = (int) (e1.getY() - e2.getY());
		if (Math.abs(dist) < SWIPE_MAX_OFF_PATH) {
			return false;
		} else {
			TermGraph tg = GridIndex.getTermGraph(e1.getX(), e2.getY());
			if (tg == null) {
				Grid g = GridIndex.getGrid(e1.getX(), e2.getY());
				if (g == null)
					return false;
				if (dist > SWIPE_MAX_OFF_PATH) {
					annotatePanel.down(dist, g);
					return true;
				} else if (e2.getY() - e1.getY() > SWIPE_MAX_OFF_PATH) {
					annotatePanel.up(dist, g);
					return true;
				} else {
					return false;
				}
			} else {
				tg.setColor(Color.BLUE);
				adjustGrid(dist, tg.getGrid(), e1, e2);
				return true;
			}
		}
	}

	private void adjustGrid(int dist, Grid grid, MotionEvent e1, MotionEvent e2) {
		if (dist > SWIPE_MAX_OFF_PATH) {
			down(dist, grid);
		} else if (e2.getY() - e1.getY() > SWIPE_MAX_OFF_PATH) {
			up(dist, grid);
		}
	}

	public void up(int dist, Grid g) {
		float incr = g.worldHeight(dist);
		g.setymax(g.getymax() - incr);
		g.setymin(g.getymin() - incr);
	}

	public void down(int dist, Grid g) {
		float incr = g.worldHeight(dist);
		g.setymax(g.getymax() - incr);
		g.setymin(g.getymin() - incr);
	}
}
